# python3
# Copyright (C) 2019 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Warning patterns for Java compiler tools."""

# No need of doc strings for trivial small functions.
# pylint:disable=missing-function-docstring

# pylint:disable=relative-beyond-top-level
from .cpp_warn_patterns import compile_patterns
from .severity import Severity


def java_warn(severity, description, pattern_list):
  return {
      'category': 'Java',
      'severity': severity,
      'description': 'Java: ' + description,
      'patterns': pattern_list
  }


def java_high(description, pattern_list):
  return java_warn(Severity.HIGH, description, pattern_list)


def java_medium(description, pattern_list):
  return java_warn(Severity.MEDIUM, description, pattern_list)


def warn_with_name(name, severity, description=None):
  if description is None:
    description = name
  return java_warn(severity, description,
                   [r'.*\.java:.*: warning: .+ \[' + name + r'\]$',
                    r'.*\.java:.*: warning: \[' + name + r'\] .+'])


def high(name, description=None):
  return warn_with_name(name, Severity.HIGH, description)


def medium(name, description=None):
  return warn_with_name(name, Severity.MEDIUM, description)


def low(name, description=None):
  return warn_with_name(name, Severity.LOW, description)


warn_patterns = [
    # pylint does not recognize g-inconsistent-quotes
    # pylint:disable=line-too-long,bad-option-value,g-inconsistent-quotes
    # Warnings from Javac
    java_medium('Use of deprecated',
                [r'.*: warning: \[deprecation\] .+',
                 r'.*: warning: \[removal\] .+ has been deprecated and marked for removal$']),
    java_medium('Incompatible SDK implementation',
                [r'.*\.java:.*: warning: @Implementation .+ has .+ not .+ as in the SDK ']),
    medium('unchecked', 'Unchecked conversion'),
    java_medium('No annotation method',
                [r'.*\.class\): warning: Cannot find annotation method .+ in']),
    java_medium('No class/method in SDK ...',
                [r'.*\.java:.*: warning: No such (class|method) .* for SDK']),
    # Warnings generated by Error Prone
    java_medium('Non-ascii characters used, but ascii encoding specified',
                [r".*: warning: unmappable character for encoding ascii"]),
    java_medium('Non-varargs call of varargs method with inexact argument type for last parameter',
                [r".*: warning: non-varargs call of varargs method with inexact argument type for last parameter"]),
    java_medium('Unchecked method invocation',
                [r".*: warning: \[unchecked\] unchecked method invocation: .+ in class .+"]),
    java_medium('Unchecked conversion',
                [r".*: warning: \[unchecked\] unchecked conversion"]),
    java_medium('_ used as an identifier',
                [r".*: warning: '_' used as an identifier"]),
    java_medium('hidden superclass',
                [r".*: warning: .* stripped of .* superclass .* \[HiddenSuperclass\]"]),
    java_high('Use of internal proprietary API',
              [r".*: warning: .* is internal proprietary API and may be removed"]),
    low('BooleanParameter',
        'Use parameter comments to document ambiguous literals'),
    low('ClassNamedLikeTypeParameter',
        'This class\'s name looks like a Type Parameter.'),
    low('ConstantField',
        'Field name is CONSTANT_CASE, but field is not static and final'),
    low('EmptySetMultibindingContributions',
        '@Multibinds is a more efficient and declarative mechanism for ensuring that a set multibinding is present in the graph.'),
    low('ExpectedExceptionRefactoring',
        'Prefer assertThrows to ExpectedException'),
    low('FieldCanBeFinal',
        'This field is only assigned during initialization; consider making it final'),
    low('FieldMissingNullable',
        'Fields that can be null should be annotated @Nullable'),
    low('ImmutableRefactoring',
        'Refactors uses of the JSR 305 @Immutable to Error Prone\'s annotation'),
    low('LambdaFunctionalInterface',
        u'Use Java\'s utility functional interfaces instead of Function\u003cA, B> for primitive types.'),
    low('MethodCanBeStatic',
        'A private method that does not reference the enclosing instance can be static'),
    low('MixedArrayDimensions',
        'C-style array declarations should not be used'),
    low('MultiVariableDeclaration',
        'Variable declarations should declare only one variable'),
    low('MultipleTopLevelClasses',
        'Source files should not contain multiple top-level class declarations'),
    low('MultipleUnaryOperatorsInMethodCall',
        'Avoid having multiple unary operators acting on the same variable in a method call'),
    low('OnNameExpected',
        'OnNameExpected naming style'),
    low('PackageLocation',
        'Package names should match the directory they are declared in'),
    low('ParameterComment',
        'Non-standard parameter comment; prefer `/* paramName= */ arg`'),
    low('ParameterNotNullable',
        'Method parameters that aren\'t checked for null shouldn\'t be annotated @Nullable'),
    low('PrivateConstructorForNoninstantiableModule',
        'Add a private constructor to modules that will not be instantiated by Dagger.'),
    low('PrivateConstructorForUtilityClass',
        'Utility classes (only static members) are not designed to be instantiated and should be made noninstantiable with a default constructor.'),
    low('RemoveUnusedImports',
        'Unused imports'),
    low('ReturnMissingNullable',
        'Methods that can return null should be annotated @Nullable'),
    low('ScopeOnModule',
        'Scopes on modules have no function and will soon be an error.'),
    low('SwitchDefault',
        'The default case of a switch should appear at the end of the last statement group'),
    low('TestExceptionRefactoring',
        'Prefer assertThrows to @Test(expected=...)'),
    low('ThrowsUncheckedException',
        'Unchecked exceptions do not need to be declared in the method signature.'),
    low('TryFailRefactoring',
        'Prefer assertThrows to try/fail'),
    low('TypeParameterNaming',
        'Type parameters must be a single letter with an optional numeric suffix, or an UpperCamelCase name followed by the letter \'T\'.'),
    low('UngroupedOverloads',
        'Constructors and methods with the same name should appear sequentially with no other code in between. Please re-order or re-name methods.'),
    low('UnnecessarySetDefault',
        'Unnecessary call to NullPointerTester#setDefault'),
    low('UnnecessaryStaticImport',
        'Using static imports for types is unnecessary'),
    low('UseBinds',
        '@Binds is a more efficient and declarative mechanism for delegating a binding.'),
    low('WildcardImport',
        'Wildcard imports, static or otherwise, should not be used'),
    medium('AcronymName',
           'AcronymName'),
    medium('AmbiguousMethodReference',
           'Method reference is ambiguous'),
    medium('AnnotateFormatMethod',
           'This method passes a pair of parameters through to String.format, but the enclosing method wasn\'t annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings.'),
    medium('AnnotationPosition',
           'Annotations should be positioned after Javadocs, but before modifiers..'),
    medium('ArgumentSelectionDefectChecker',
           'Arguments are in the wrong order or could be commented for clarity.'),
    medium('ArrayAsKeyOfSetOrMap',
           'Arrays do not override equals() or hashCode, so comparisons will be done on reference equality only. If neither deduplication nor lookup are needed, consider using a List instead. Otherwise, use IdentityHashMap/Set, a Map from a library that handles object arrays, or an Iterable/List of pairs.'),
    medium('AssertEqualsArgumentOrderChecker',
           'Arguments are swapped in assertEquals-like call'),
    medium('AssertFalse',
           'Assertions may be disabled at runtime and do not guarantee that execution will halt here; consider throwing an exception instead'),
    medium('AssertThrowsMultipleStatements',
           'The lambda passed to assertThrows should contain exactly one statement'),
    medium('AssertionFailureIgnored',
           'This assertion throws an AssertionError if it fails, which will be caught by an enclosing try block.'),
    medium('AssistedInjectAndInjectOnConstructors',
           '@AssistedInject and @Inject should not be used on different constructors in the same class.'),
    medium('AutoValueFinalMethods',
           'Make toString(), hashCode() and equals() final in AutoValue classes, so it is clear to readers that AutoValue is not overriding them'),
    medium('BadAnnotationImplementation',
           'Classes that implement Annotation must override equals and hashCode. Consider using AutoAnnotation instead of implementing Annotation by hand.'),
    medium('BadComparable',
           'Possible sign flip from narrowing conversion'),
    medium('BadImport',
           'Importing nested classes/static methods/static fields with commonly-used names can make code harder to read, because it may not be clear from the context exactly which type is being referred to. Qualifying the name with that of the containing class can make the code clearer.'),
    medium('BadInstanceof',
           'instanceof used in a way that is equivalent to a null check.'),
    medium('BigDecimalEquals',
           'BigDecimal#equals has surprising behavior: it also compares scale.'),
    medium('BigDecimalLiteralDouble',
           'new BigDecimal(double) loses precision in this case.'),
    medium('BinderIdentityRestoredDangerously',
           'A call to Binder.clearCallingIdentity() should be followed by Binder.restoreCallingIdentity() in a finally block. Otherwise the wrong Binder identity may be used by subsequent code.'),
    medium('BindingToUnqualifiedCommonType',
           'This code declares a binding for a common value type without a Qualifier annotation.'),
    medium('BoxedPrimitiveConstructor',
           'valueOf or autoboxing provides better time and space performance'),
    medium('ByteBufferBackingArray',
           'ByteBuffer.array() shouldn\'t be called unless ByteBuffer.arrayOffset() is used or if the ByteBuffer was initialized using ByteBuffer.wrap() or ByteBuffer.allocate().'),
    medium('CannotMockFinalClass',
           'Mockito cannot mock final classes'),
    medium('CanonicalDuration',
           'Duration can be expressed more clearly with different units'),
    medium('CatchAndPrintStackTrace',
           'Logging or rethrowing exceptions should usually be preferred to catching and calling printStackTrace'),
    medium('CatchFail',
           'Ignoring exceptions and calling fail() is unnecessary, and makes test output less useful'),
    medium('ClassCanBeStatic',
           'Inner class is non-static but does not reference enclosing class'),
    medium('ClassNewInstance',
           'Class.newInstance() bypasses exception checking; prefer getDeclaredConstructor().newInstance()'),
    medium('CloseableProvides',
           'Providing Closeable resources makes their lifecycle unclear'),
    medium('CollectionToArraySafeParameter',
           'The type of the array parameter of Collection.toArray needs to be compatible with the array type'),
    medium('CollectorShouldNotUseState',
           'Collector.of() should not use state'),
    medium('ComparableAndComparator',
           'Class should not implement both `Comparable` and `Comparator`'),
    medium('ConstructorInvokesOverridable',
           'Constructors should not invoke overridable methods.'),
    medium('ConstructorLeaksThis',
           'Constructors should not pass the \'this\' reference out in method invocations, since the object may not be fully constructed.'),
    medium('DateFormatConstant',
           'DateFormat is not thread-safe, and should not be used as a constant field.'),
    medium('DefaultCharset',
           'Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn\'t match expectations.'),
    medium('DeprecatedThreadMethods',
           'Avoid deprecated Thread methods; read the method\'s javadoc for details.'),
    medium('DoubleBraceInitialization',
           'Prefer collection factory methods or builders to the double-brace initialization pattern.'),
    medium('DoubleCheckedLocking',
           'Double-checked locking on non-volatile fields is unsafe'),
    medium('EmptyTopLevelDeclaration',
           'Empty top-level type declaration'),
    medium('EqualsBrokenForNull',
           'equals() implementation may throw NullPointerException when given null'),
    medium('EqualsGetClass',
           'Overriding Object#equals in a non-final class by using getClass rather than instanceof breaks substitutability of subclasses.'),
    medium('EqualsHashCode',
           'Classes that override equals should also override hashCode.'),
    medium('EqualsIncompatibleType',
           'An equality test between objects with incompatible types always returns false'),
    medium('EqualsUnsafeCast',
           'The contract of #equals states that it should return false for incompatible types, while this implementation may throw ClassCastException.'),
    medium('EqualsUsingHashCode',
           'Implementing #equals by just comparing hashCodes is fragile. Hashes collide frequently, and this will lead to false positives in #equals.'),
    medium('ExpectedExceptionChecker',
           'Calls to ExpectedException#expect should always be followed by exactly one statement.'),
    medium('ExtendingJUnitAssert',
           'When only using JUnit Assert\'s static methods, you should import statically instead of extending.'),
    medium('FallThrough',
           'Switch case may fall through'),
    medium('Finally',
           'If you return or throw from a finally, then values returned or thrown from the try-catch block will be ignored. Consider using try-with-resources instead.'),
    medium('FloatCast',
           'Use parentheses to make the precedence explicit'),
    medium('FloatingPointAssertionWithinEpsilon',
           'This fuzzy equality check is using a tolerance less than the gap to the next number. You may want a less restrictive tolerance, or to assert equality.'),
    medium('FloatingPointLiteralPrecision',
           'Floating point literal loses precision'),
    medium('FragmentInjection',
           'Classes extending PreferenceActivity must implement isValidFragment such that it does not unconditionally return true to prevent vulnerability to fragment injection attacks.'),
    medium('FragmentNotInstantiable',
           'Subclasses of Fragment must be instantiable via Class#newInstance(): the class must be public, static and have a public nullary constructor'),
    medium('FunctionalInterfaceClash',
           'Overloads will be ambiguous when passing lambda arguments'),
    medium('FutureReturnValueIgnored',
           'Return value of methods returning Future must be checked. Ignoring returned Futures suppresses exceptions thrown from the code that completes the Future.'),
    medium('GetClassOnEnum',
           'Calling getClass() on an enum may return a subclass of the enum type'),
    medium('HardCodedSdCardPath',
           'Hardcoded reference to /sdcard'),
    medium('HidingField',
           'Hiding fields of superclasses may cause confusion and errors'),
    medium('ImmutableAnnotationChecker',
           'Annotations should always be immutable'),
    medium('ImmutableEnumChecker',
           'Enums should always be immutable'),
    medium('IncompatibleModifiers',
           'This annotation has incompatible modifiers as specified by its @IncompatibleModifiers annotation'),
    medium('InconsistentCapitalization',
           'It is confusing to have a field and a parameter under the same scope that differ only in capitalization.'),
    medium('InconsistentHashCode',
           'Including fields in hashCode which are not compared in equals violates the contract of hashCode.'),
    medium('InconsistentOverloads',
           'The ordering of parameters in overloaded methods should be as consistent as possible (when viewed from left to right)'),
    medium('IncrementInForLoopAndHeader',
           'This for loop increments the same variable in the header and in the body'),
    medium('InjectOnConstructorOfAbstractClass',
           'Constructors on abstract classes are never directly @Injected, only the constructors of their subclasses can be @Inject\'ed.'),
    medium('InputStreamSlowMultibyteRead',
           'Please also override int read(byte[], int, int), otherwise multi-byte reads from this input stream are likely to be slow.'),
    medium('InstanceOfAndCastMatchWrongType',
           'Casting inside an if block should be plausibly consistent with the instanceof type'),
    medium('IntLongMath',
           'Expression of type int may overflow before being assigned to a long'),
    medium('IntentBuilderName',
           'IntentBuilderName'),
    medium('InvalidParam',
           'This @param tag doesn\'t refer to a parameter of the method.'),
    medium('InvalidTag',
           'This tag is invalid.'),
    medium('InvalidThrows',
           'The documented method doesn\'t actually throw this checked exception.'),
    medium('IterableAndIterator',
           'Class should not implement both `Iterable` and `Iterator`'),
    medium('JUnit3FloatingPointComparisonWithoutDelta',
           'Floating-point comparison without error tolerance'),
    medium('JUnit4ClassUsedInJUnit3',
           'Some JUnit4 construct cannot be used in a JUnit3 context. Convert your class to JUnit4 style to use them.'),
    medium('JUnitAmbiguousTestClass',
           'Test class inherits from JUnit 3\'s TestCase but has JUnit 4 @Test annotations.'),
    medium('JavaLangClash',
           'Never reuse class names from java.lang'),
    medium('JdkObsolete',
           'Suggests alternatives to obsolete JDK classes.'),
    medium('LockNotBeforeTry',
           'Calls to Lock#lock should be immediately followed by a try block which releases the lock.'),
    medium('LogicalAssignment',
           'Assignment where a boolean expression was expected; use == if this assignment wasn\'t expected or add parentheses for clarity.'),
    medium('MathAbsoluteRandom',
           'Math.abs does not always give a positive result. Please consider other methods for positive random numbers.'),
    medium('MissingCasesInEnumSwitch',
           'Switches on enum types should either handle all values, or have a default case.'),
    medium('MissingDefault',
           'The Google Java Style Guide requires that each switch statement includes a default statement group, even if it contains no code. (This requirement is lifted for any switch statement that covers all values of an enum.)'),
    medium('MissingFail',
           'Not calling fail() when expecting an exception masks bugs'),
    medium('MissingOverride',
           'method overrides method in supertype; expected @Override'),
    medium('ModifiedButNotUsed',
           'A collection or proto builder was created, but its values were never accessed.'),
    medium('ModifyCollectionInEnhancedForLoop',
           'Modifying a collection while iterating over it in a loop may cause a ConcurrentModificationException to be thrown.'),
    medium('MultipleParallelOrSequentialCalls',
           'Multiple calls to either parallel or sequential are unnecessary and cause confusion.'),
    medium('MutableConstantField',
           'Constant field declarations should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)'),
    medium('MutableMethodReturnType',
           'Method return type should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)'),
    medium('NarrowingCompoundAssignment',
           'Compound assignments may hide dangerous casts'),
    medium('NestedInstanceOfConditions',
           'Nested instanceOf conditions of disjoint types create blocks of code that never execute'),
    medium('NoFunctionalReturnType',
           'Instead of returning a functional type, return the actual type that the returned function would return and use lambdas at use site.'),
    medium('NonAtomicVolatileUpdate',
           'This update of a volatile variable is non-atomic'),
    medium('NonCanonicalStaticMemberImport',
           'Static import of member uses non-canonical name'),
    medium('NonOverridingEquals',
           'equals method doesn\'t override Object.equals'),
    medium('NotCloseable',
           'Not closeable'),
    medium('NullableConstructor',
           'Constructors should not be annotated with @Nullable since they cannot return null'),
    medium('NullableDereference',
           'Dereference of possibly-null value'),
    medium('NullablePrimitive',
           '@Nullable should not be used for primitive types since they cannot be null'),
    medium('NullableVoid',
           'void-returning methods should not be annotated with @Nullable, since they cannot return null'),
    medium('ObjectToString',
           'Calling toString on Objects that don\'t override toString() doesn\'t provide useful information'),
    medium('ObjectsHashCodePrimitive',
           'Objects.hashCode(Object o) should not be passed a primitive value'),
    medium('OperatorPrecedence',
           'Use grouping parenthesis to make the operator precedence explicit'),
    medium('OptionalNotPresent',
           'One should not call optional.get() inside an if statement that checks !optional.isPresent'),
    medium('OrphanedFormatString',
           'String literal contains format specifiers, but is not passed to a format method'),
    medium('OverrideThrowableToString',
           'To return a custom message with a Throwable class, one should override getMessage() instead of toString() for Throwable.'),
    medium('Overrides',
           'Varargs doesn\'t agree for overridden method'),
    medium('OverridesGuiceInjectableMethod',
           'This method is not annotated with @Inject, but it overrides a method that is annotated with @com.google.inject.Inject. Guice will inject this method, and it is recommended to annotate it explicitly.'),
    medium('ParameterName',
           'Detects `/* name= */`-style comments on actual parameters where the name doesn\'t match the formal parameter'),
    medium('PreconditionsInvalidPlaceholder',
           'Preconditions only accepts the %s placeholder in error message strings'),
    medium('PrimitiveArrayPassedToVarargsMethod',
           'Passing a primitive array to a varargs method is usually wrong'),
    medium('ProtoRedundantSet',
           'A field on a protocol buffer was set twice in the same chained expression.'),
    medium('ProtosAsKeyOfSetOrMap',
           'Protos should not be used as a key to a map, in a set, or in a contains method on a descendant of a collection. Protos have non deterministic ordering and proto equality is deep, which is a performance issue.'),
    medium('ProvidesFix',
           'BugChecker has incorrect ProvidesFix tag, please update'),
    medium('QualifierOrScopeOnInjectMethod',
           'Qualifiers/Scope annotations on @Inject methods don\'t have any effect. Move the qualifier annotation to the binding location.'),
    medium('QualifierWithTypeUse',
           'Injection frameworks currently don\'t understand Qualifiers in TYPE_PARAMETER or TYPE_USE contexts.'),
    medium('ReachabilityFenceUsage',
           'reachabilityFence should always be called inside a finally block'),
    medium('RedundantThrows',
           'Thrown exception is a subtype of another'),
    medium('ReferenceEquality',
           'Comparison using reference equality instead of value equality'),
    medium('RequiredModifiers',
           'This annotation is missing required modifiers as specified by its @RequiredModifiers annotation'),
    medium('ReturnFromVoid',
           'Void methods should not have a @return tag.'),
    medium('SamShouldBeLast',
           'SAM-compatible parameters should be last'),
    medium('ShortCircuitBoolean',
           u'Prefer the short-circuiting boolean operators \u0026\u0026 and || to \u0026 and |.'),
    medium('StaticGuardedByInstance',
           'Writes to static fields should not be guarded by instance locks'),
    medium('StaticQualifiedUsingExpression',
           'A static variable or method should be qualified with a class name, not expression'),
    medium('StreamResourceLeak',
           'Streams that encapsulate a closeable resource should be closed using try-with-resources'),
    medium('StringEquality',
           'String comparison using reference equality instead of value equality'),
    medium('StringSplitter',
           'String.split(String) has surprising behavior'),
    medium('SwigMemoryLeak',
           'SWIG generated code that can\'t call a C++ destructor will leak memory'),
    medium('SynchronizeOnNonFinalField',
           'Synchronizing on non-final fields is not safe: if the field is ever updated, different threads may end up locking on different objects.'),
    medium('SystemExitOutsideMain',
           'Code that contains System.exit() is untestable.'),
    medium('TestExceptionChecker',
           'Using @Test(expected=...) is discouraged, since the test will pass if *any* statement in the test method throws the expected exception'),
    medium('ThreadJoinLoop',
           'Thread.join needs to be surrounded by a loop until it succeeds, as in Uninterruptibles.joinUninterruptibly.'),
    medium('ThreadLocalUsage',
           'ThreadLocals should be stored in static fields'),
    medium('ThreadPriorityCheck',
           'Relying on the thread scheduler is discouraged; see Effective Java Item 72 (2nd edition) / 84 (3rd edition).'),
    medium('ThreeLetterTimeZoneID',
           'Three-letter time zone identifiers are deprecated, may be ambiguous, and might not do what you intend; the full IANA time zone ID should be used instead.'),
    medium('ToStringReturnsNull',
           'An implementation of Object.toString() should never return null.'),
    medium('TruthAssertExpected',
           'The actual and expected values appear to be swapped, which results in poor assertion failure messages. The actual value should come first.'),
    medium('TruthConstantAsserts',
           'Truth Library assert is called on a constant.'),
    medium('TruthIncompatibleType',
           'Argument is not compatible with the subject\'s type.'),
    medium('TypeNameShadowing',
           'Type parameter declaration shadows another named type'),
    medium('TypeParameterShadowing',
           'Type parameter declaration overrides another type parameter already declared'),
    medium('TypeParameterUnusedInFormals',
           'Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution.'),
    medium('URLEqualsHashCode',
           'Avoid hash-based containers of java.net.URL--the containers rely on equals() and hashCode(), which cause java.net.URL to make blocking internet connections.'),
    medium('UndefinedEquals',
           'Collection, Iterable, Multimap, and Queue do not have well-defined equals behavior'),
    medium('UnnecessaryDefaultInEnumSwitch',
           'Switch handles all enum values: an explicit default case is unnecessary and defeats error checking for non-exhaustive switches.'),
    medium('UnnecessaryParentheses',
           'Unnecessary use of grouping parentheses'),
    medium('UnsafeFinalization',
           'Finalizer may run before native code finishes execution'),
    medium('UnsafeReflectiveConstructionCast',
           'Prefer `asSubclass` instead of casting the result of `newInstance`, to detect classes of incorrect type before invoking their constructors.This way, if the class is of the incorrect type,it will throw an exception before invoking its constructor.'),
    medium('UnsynchronizedOverridesSynchronized',
           'Unsynchronized method overrides a synchronized method.'),
    medium('Unused',
           'Unused.'),
    medium('UnusedException',
           'This catch block catches an exception and re-throws another, but swallows the caught exception rather than setting it as a cause. This can make debugging harder.'),
    medium('UseCorrectAssertInTests',
           'Java assert is used in test. For testing purposes Assert.* matchers should be used.'),
    medium('UserHandle',
           'UserHandle'),
    medium('UserHandleName',
           'UserHandleName'),
    medium('Var',
           'Non-constant variable missing @Var annotation'),
    medium('VariableNameSameAsType',
           'variableName and type with the same name would refer to the static field instead of the class'),
    medium('WaitNotInLoop',
           'Because of spurious wakeups, Object.wait() and Condition.await() must always be called in a loop'),
    medium('WakelockReleasedDangerously',
           'A wakelock acquired with a timeout may be released by the system before calling `release`, even after checking `isHeld()`. If so, it will throw a RuntimeException. Please wrap in a try/catch block.'),
    java_medium('Found raw type',
                [r'.*\.java:.*: warning: \[rawtypes\] found raw type']),
    java_medium('Redundant cast',
                [r'.*\.java:.*: warning: \[cast\] redundant cast to']),
    java_medium('Static method should be qualified',
                [r'.*\.java:.*: warning: \[static\] static method should be qualified']),
    medium('AbstractInner'),
    medium('BothPackageInfoAndHtml'),
    medium('BuilderSetStyle'),
    medium('CallbackName'),
    medium('ExecutorRegistration'),
    medium('HiddenTypeParameter'),
    medium('JavaApiUsedByMainlineModule'),
    medium('ListenerLast'),
    medium('MinMaxConstant'),
    medium('MissingBuildMethod'),
    medium('MissingGetterMatchingBuilder'),
    medium('NoByteOrShort'),
    medium('OverlappingConstants'),
    medium('SetterReturnsThis'),
    medium('StaticFinalBuilder'),
    medium('StreamFiles'),
    medium('Typo'),
    medium('UseIcu'),
    medium('fallthrough'),
    medium('overrides'),
    medium('serial'),
    medium('try'),
    high('AndroidInjectionBeforeSuper',
         'AndroidInjection.inject() should always be invoked before calling super.lifecycleMethod()'),
    high('AndroidJdkLibsChecker',
         'Use of class, field, or method that is not compatible with legacy Android devices'),
    high('ArrayEquals',
         'Reference equality used to compare arrays'),
    high('ArrayFillIncompatibleType',
         'Arrays.fill(Object[], Object) called with incompatible types.'),
    high('ArrayHashCode',
         'hashcode method on array does not hash array contents'),
    high('ArrayReturn',
         'ArrayReturn'),
    high('ArrayToString',
         'Calling toString on an array does not provide useful information'),
    high('ArraysAsListPrimitiveArray',
         'Arrays.asList does not autobox primitive arrays, as one might expect.'),
    high('AssistedInjectAndInjectOnSameConstructor',
         '@AssistedInject and @Inject cannot be used on the same constructor.'),
    high('AsyncCallableReturnsNull',
         'AsyncCallable should not return a null Future, only a Future whose result is null.'),
    high('AsyncFunctionReturnsNull',
         'AsyncFunction should not return a null Future, only a Future whose result is null.'),
    high('AutoFactoryAtInject',
         '@AutoFactory and @Inject should not be used in the same type.'),
    high('AutoValueConstructorOrderChecker',
         'Arguments to AutoValue constructor are in the wrong order'),
    high('BadShiftAmount',
         'Shift by an amount that is out of range'),
    high('BundleDeserializationCast',
         'Object serialized in Bundle may have been flattened to base type.'),
    high('ChainingConstructorIgnoresParameter',
         'The called constructor accepts a parameter with the same name and type as one of its caller\'s parameters, but its caller doesn\'t pass that parameter to it.  It\'s likely that it was intended to.'),
    high('CheckReturnValue',
         'Ignored return value of method that is annotated with @CheckReturnValue'),
    high('ClassName',
         'The source file name should match the name of the top-level class it contains'),
    high('CollectionIncompatibleType',
         'Incompatible type as argument to Object-accepting Java collections method'),
    high('ComparableType',
         u'Implementing \'Comparable\u003cT>\' where T is not compatible with the implementing class.'),
    high('ComparingThisWithNull',
         'this == null is always false, this != null is always true'),
    high('ComparisonContractViolated',
         'This comparison method violates the contract'),
    high('ComparisonOutOfRange',
         'Comparison to value that is out of range for the compared type'),
    high('CompatibleWithAnnotationMisuse',
         '@CompatibleWith\'s value is not a type argument.'),
    high('CompileTimeConstant',
         'Non-compile-time constant expression passed to parameter with @CompileTimeConstant type annotation.'),
    high('ComplexBooleanConstant',
         'Non-trivial compile time constant boolean expressions shouldn\'t be used.'),
    high('ConditionalExpressionNumericPromotion',
         'A conditional expression with numeric operands of differing types will perform binary numeric promotion of the operands; when these operands are of reference types, the expression\'s result may not be of the expected type.'),
    high('ConstantOverflow',
         'Compile-time constant expression overflows'),
    high('DaggerProvidesNull',
         'Dagger @Provides methods may not return null unless annotated with @Nullable'),
    high('DeadException',
         'Exception created but not thrown'),
    high('DeadThread',
         'Thread created but not started'),
    java_high('Deprecated item is not annotated with @Deprecated',
              [r".*\.java:.*: warning: \[.*\] .+ is not annotated with @Deprecated$"]),
    high('DivZero',
         'Division by integer literal zero'),
    high('DoNotCall',
         'This method should not be called.'),
    high('EmptyIf',
         'Empty statement after if'),
    high('EqualsNaN',
         '== NaN always returns false; use the isNaN methods instead'),
    high('EqualsReference',
         '== must be used in equals method to check equality to itself or an infinite loop will occur.'),
    high('EqualsWrongThing',
         'Comparing different pairs of fields/getters in an equals implementation is probably a mistake.'),
    high('ForOverride',
         'Method annotated @ForOverride must be protected or package-private and only invoked from declaring class, or from an override of the method'),
    high('FormatString',
         'Invalid printf-style format string'),
    high('FormatStringAnnotation',
         'Invalid format string passed to formatting method.'),
    high('FunctionalInterfaceMethodChanged',
         'Casting a lambda to this @FunctionalInterface can cause a behavior change from casting to a functional superinterface, which is surprising to users.  Prefer decorator methods to this surprising behavior.'),
    high('FuturesGetCheckedIllegalExceptionType',
         'Futures.getChecked requires a checked exception type with a standard constructor.'),
    high('FuzzyEqualsShouldNotBeUsedInEqualsMethod',
         'DoubleMath.fuzzyEquals should never be used in an Object.equals() method'),
    high('GetClassOnAnnotation',
         'Calling getClass() on an annotation may return a proxy class'),
    high('GetClassOnClass',
         'Calling getClass() on an object of type Class returns the Class object for java.lang.Class; you probably meant to operate on the object directly'),
    high('GuardedBy',
         'Checks for unguarded accesses to fields and methods with @GuardedBy annotations'),
    high('GuiceAssistedInjectScoping',
         'Scope annotation on implementation class of AssistedInject factory is not allowed'),
    high('GuiceAssistedParameters',
         'A constructor cannot have two @Assisted parameters of the same type unless they are disambiguated with named @Assisted annotations.'),
    high('GuiceInjectOnFinalField',
         'Although Guice allows injecting final fields, doing so is disallowed because the injected value may not be visible to other threads.'),
    high('HashtableContains',
         'contains() is a legacy method that is equivalent to containsValue()'),
    high('IdentityBinaryExpression',
         'A binary expression where both operands are the same is usually incorrect.'),
    high('Immutable',
         'Type declaration annotated with @Immutable is not immutable'),
    high('ImmutableModification',
         'Modifying an immutable collection is guaranteed to throw an exception and leave the collection unmodified'),
    high('IncompatibleArgumentType',
         'Passing argument to a generic method with an incompatible type.'),
    high('IndexOfChar',
         'The first argument to indexOf is a Unicode code point, and the second is the index to start the search from'),
    high('InexactVarargsConditional',
         'Conditional expression in varargs call contains array and non-array arguments'),
    high('InfiniteRecursion',
         'This method always recurses, and will cause a StackOverflowError'),
    high('InjectInvalidTargetingOnScopingAnnotation',
         'A scoping annotation\'s Target should include TYPE and METHOD.'),
    high('InjectMoreThanOneQualifier',
         'Using more than one qualifier annotation on the same element is not allowed.'),
    high('InjectMoreThanOneScopeAnnotationOnClass',
         'A class can be annotated with at most one scope annotation.'),
    high('InjectOnMemberAndConstructor',
         'Members shouldn\'t be annotated with @Inject if constructor is already annotated @Inject'),
    high('InjectScopeAnnotationOnInterfaceOrAbstractClass',
         'Scope annotation on an interface or abstact class is not allowed'),
    high('InjectScopeOrQualifierAnnotationRetention',
         'Scoping and qualifier annotations must have runtime retention.'),
    high('InjectedConstructorAnnotations',
         'Injected constructors cannot be optional nor have binding annotations'),
    high('InsecureCryptoUsage',
         'A standard cryptographic operation is used in a mode that is prone to vulnerabilities'),
    high('InvalidPatternSyntax',
         'Invalid syntax used for a regular expression'),
    high('InvalidTimeZoneID',
         'Invalid time zone identifier. TimeZone.getTimeZone(String) will silently return GMT instead of the time zone you intended.'),
    high('IsInstanceOfClass',
         'The argument to Class#isInstance(Object) should not be a Class'),
    high('IsLoggableTagLength',
         'Log tag too long, cannot exceed 23 characters.'),
    high('IterablePathParameter',
         u'Path implements Iterable\u003cPath>; prefer Collection\u003cPath> for clarity'),
    high('JMockTestWithoutRunWithOrRuleAnnotation',
         'jMock tests must have a @RunWith(JMock.class) annotation, or the Mockery field must have a @Rule JUnit annotation'),
    high('JUnit3TestNotRun',
         'Test method will not be run; please correct method signature (Should be public, non-static, and method name should begin with "test").'),
    high('JUnit4ClassAnnotationNonStatic',
         'This method should be static'),
    high('JUnit4SetUpNotRun',
         'setUp() method will not be run; please add JUnit\'s @Before annotation'),
    high('JUnit4TearDownNotRun',
         'tearDown() method will not be run; please add JUnit\'s @After annotation'),
    high('JUnit4TestNotRun',
         'This looks like a test method but is not run; please add @Test and @Ignore, or, if this is a helper method, reduce its visibility.'),
    high('JUnitAssertSameCheck',
         'An object is tested for reference equality to itself using JUnit library.'),
    high('Java7ApiChecker',
         'Use of class, field, or method that is not compatible with JDK 7'),
    high('JavaxInjectOnAbstractMethod',
         'Abstract and default methods are not injectable with javax.inject.Inject'),
    high('JavaxInjectOnFinalField',
         '@javax.inject.Inject cannot be put on a final field.'),
    high('LiteByteStringUtf8',
         'This pattern will silently corrupt certain byte sequences from the serialized protocol message. Use ByteString or byte[] directly'),
    high('LockMethodChecker',
         'This method does not acquire the locks specified by its @LockMethod annotation'),
    high('LongLiteralLowerCaseSuffix',
         'Prefer \'L\' to \'l\' for the suffix to long literals'),
    high('LoopConditionChecker',
         'Loop condition is never modified in loop body.'),
    high('MathRoundIntLong',
         'Math.round(Integer) results in truncation'),
    high('MislabeledAndroidString',
         'Certain resources in `android.R.string` have names that do not match their content'),
    high('MissingSuperCall',
         'Overriding method is missing a call to overridden super method'),
    high('MissingTestCall',
         'A terminating method call is required for a test helper to have any effect.'),
    high('MisusedWeekYear',
         'Use of "YYYY" (week year) in a date pattern without "ww" (week in year). You probably meant to use "yyyy" (year) instead.'),
    high('MockitoCast',
         'A bug in Mockito will cause this test to fail at runtime with a ClassCastException'),
    high('MockitoUsage',
         'Missing method call for verify(mock) here'),
    high('ModifyingCollectionWithItself',
         'Using a collection function with itself as the argument.'),
    high('MoreThanOneInjectableConstructor',
         'This class has more than one @Inject-annotated constructor. Please remove the @Inject annotation from all but one of them.'),
    high('MustBeClosedChecker',
         'The result of this method must be closed.'),
    high('NCopiesOfChar',
         'The first argument to nCopies is the number of copies, and the second is the item to copy'),
    high('NoAllocation',
         '@NoAllocation was specified on this method, but something was found that would trigger an allocation'),
    high('NonCanonicalStaticImport',
         'Static import of type uses non-canonical name'),
    high('NonFinalCompileTimeConstant',
         '@CompileTimeConstant parameters should be final or effectively final'),
    high('NonRuntimeAnnotation',
         'Calling getAnnotation on an annotation that is not retained at runtime.'),
    high('NullTernary',
         'This conditional expression may evaluate to null, which will result in an NPE when the result is unboxed.'),
    high('NumericEquality',
         'Numeric comparison using reference equality instead of value equality'),
    high('OptionalEquality',
         'Comparison using reference equality instead of value equality'),
    high('OverlappingQualifierAndScopeAnnotation',
         'Annotations cannot be both Scope annotations and Qualifier annotations: this causes confusion when trying to use them.'),
    high('OverridesJavaxInjectableMethod',
         'This method is not annotated with @Inject, but it overrides a method that is  annotated with @javax.inject.Inject. The method will not be Injected.'),
    high('PackageInfo',
         'Declaring types inside package-info.java files is very bad form'),
    high('ParameterPackage',
         'Method parameter has wrong package'),
    high('ParcelableCreator',
         'Detects classes which implement Parcelable but don\'t have CREATOR'),
    high('PreconditionsCheckNotNull',
         'Literal passed as first argument to Preconditions.checkNotNull() can never be null'),
    high('PreconditionsCheckNotNullPrimitive',
         'First argument to `Preconditions.checkNotNull()` is a primitive rather than an object reference'),
    high('PredicateIncompatibleType',
         'Using ::equals or ::isInstance as an incompatible Predicate; the predicate will always return false'),
    high('PrivateSecurityContractProtoAccess',
         'Access to a private protocol buffer field is forbidden. This protocol buffer carries a security contract, and can only be created using an approved library. Direct access to the fields is forbidden.'),
    high('ProtoFieldNullComparison',
         'Protobuf fields cannot be null.'),
    high('ProtoStringFieldReferenceEquality',
         'Comparing protobuf fields of type String using reference equality'),
    high('ProtocolBufferOrdinal',
         'To get the tag number of a protocol buffer enum, use getNumber() instead.'),
    high('ProvidesMethodOutsideOfModule',
         '@Provides methods need to be declared in a Module to have any effect.'),
    high('RandomCast',
         'Casting a random number in the range [0.0, 1.0) to an integer or long always results in 0.'),
    high('RandomModInteger',
         'Use Random.nextInt(int).  Random.nextInt() % n can have negative results'),
    high('RectIntersectReturnValueIgnored',
         'Return value of android.graphics.Rect.intersect() must be checked'),
    high('RestrictTo',
         'Use of method or class annotated with @RestrictTo'),
    high('RestrictedApiChecker',
         ' Check for non-whitelisted callers to RestrictedApiChecker.'),
    high('ReturnValueIgnored',
         'Return value of this method must be used'),
    high('SelfAssignment',
         'Variable assigned to itself'),
    high('SelfComparison',
         'An object is compared to itself'),
    high('SelfEquals',
         'Testing an object for equality with itself will always be true.'),
    high('ShouldHaveEvenArgs',
         'This method must be called with an even number of arguments.'),
    high('SizeGreaterThanOrEqualsZero',
         'Comparison of a size >= 0 is always true, did you intend to check for non-emptiness?'),
    high('StaticOrDefaultInterfaceMethod',
         'Static and default interface methods are not natively supported on older Android devices. '),
    high('StreamToString',
         'Calling toString on a Stream does not provide useful information'),
    high('StringBuilderInitWithChar',
         'StringBuilder does not have a char constructor; this invokes the int constructor.'),
    high('SubstringOfZero',
         'String.substring(0) returns the original String'),
    high('SuppressWarningsDeprecated',
         'Suppressing "deprecated" is probably a typo for "deprecation"'),
    high('ThrowIfUncheckedKnownChecked',
         'throwIfUnchecked(knownCheckedException) is a no-op.'),
    high('ThrowNull',
         'Throwing \'null\' always results in a NullPointerException being thrown.'),
    high('TruthSelfEquals',
         'isEqualTo should not be used to test an object for equality with itself; the assertion will never fail.'),
    high('TryFailThrowable',
         'Catching Throwable/Error masks failures from fail() or assert*() in the try block'),
    high('TypeParameterQualifier',
         'Type parameter used as type qualifier'),
    high('UnlockMethod',
         'This method does not acquire the locks specified by its @UnlockMethod annotation'),
    high('UnnecessaryTypeArgument',
         'Non-generic methods should not be invoked with type arguments'),
    high('UnusedAnonymousClass',
         'Instance created but never used'),
    high('UnusedCollectionModifiedInPlace',
         'Collection is modified in place, but the result is not used'),
    high('VarTypeName',
         '`var` should not be used as a type name.'),

    # Other javac tool warnings
    java_medium('addNdkApiCoverage failed to getPackage',
                [r".*: warning: addNdkApiCoverage failed to getPackage"]),
    java_medium('bad path element',
                [r".*: warning: \[path\] bad path element .*\.jar"]),
    java_medium('Supported version from annotation processor',
                [r".*: warning: Supported source version .+ from annotation processor"]),
]

compile_patterns(warn_patterns)
